package com.fulin.daijia.common.login;

import com.fulin.daijia.common.constant.RedisConstant;
import com.fulin.daijia.common.execption.FulinException;
import com.fulin.daijia.common.result.ResultCodeEnum;
import com.fulin.daijia.common.util.AuthContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect //切面类
public class FulinLoginAspect {
    private final RedisTemplate redisTemplate;

    public FulinLoginAspect(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    // 环绕通知，登录判断
    // 切入点表达式：指定对那些规则的方法进行增强
    @Around("execution(* com.fulin.daijia.*.controller.*.*(..)) && @annotation(fulinLogin)")
    public Object login(ProceedingJoinPoint proceedingJoinPoint, FulinLogin fulinLogin) throws Throwable{
        //1 获取request对象
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) attributes;
        HttpServletRequest request = sra.getRequest();
        //2 从请求头获取token
        String token = request.getHeader("token");
        //3 判断token是否为空
        if(!StringUtils.hasText(token)){
            throw new FulinException(ResultCodeEnum.LOGIN_AUTH);
        }
        String customerId = (String) redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        if(!StringUtils.hasText(customerId)){
            throw new FulinException(ResultCodeEnum.LOGIN_AUTH);
        }
        AuthContextHolder.setUserId(Long.parseLong(customerId));
        return proceedingJoinPoint.proceed();
    }
}
